<script setup name="orderPay">
import { reactive, ref, inject } from 'vue';
import { showToast, showDialog, showLoadingToast, closeToast, showImagePreview } from 'vant';
import { getUrlParam, webRequestPayment, navigateTo } from '@/utils';
import setPageTitle from '@/utils/set-page-title';
import { CreateRemark, CreateAddress, CustomerRecord } from '../components';
import store from '@/utils/store';
import useThrottle from '@/utils/useThrottle';
import api from '@/api';
const $logger = inject('logger');

import defaultUser from '@/assets/images/default-user.png';
import defaultGood from '@/assets/images/default-good.png';

const props = defineProps({
    merchantNo: {
        type: String,
        value: ''
    }
});

const state = reactive({
    isLoading: true,
    needAddress: false, // 是否显示地址
    hasGoods: false, // 是否有商品
    customCommodityList: [], // 商品列表
    showRemarkPopup: false, //  显示备注popup
    remark: '', // 显示备注
    userAvatar: defaultUser, // 默认头像
    payMoney: '', // 支付金额
    sellerName: '', // 卖家信息
    h5PayMerchantNo: props.merchantNo, // H5 对应商户号
    isSubmit: false,
    userReceiveAddress: {
        receiveAddressId: '',
        name: '',
        phone: '',
        province: '',
        city: '',
        area: '',
        detail: ''
    },
    errorInfo: null,
    showCustomerRecord: false,
    onlyShow: false
});
const showAddressPopup = ref(false);
const addressState = reactive({
    name: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    detail: ''
});

// 获取开单收款信息
const getOrderInfo = async (callback) => {
    const orderId = getUrlParam('orderId');
    store.set('PAGE_ID', '10002'); // 设置页面ID
    try {
        const res = await api.fetchGet(
            'getOrderInfo',
            { sellerCreateOrderId: orderId },
            { hasErr: true }
        );
        const { code, data, message } = res || {};
        state.isLoading = false;
        if (code === 0) {
            const { amount, collectInfo, needAddress, customCommodityList } = data;
            const {
                sellerTeamId,
                sellerInfo,
                userReceiveAddress = {},
                buyerImageHerderList,
                lastPayTime,
                payCount
            } = collectInfo || {};
            state.payMoney = amount;
            state.sellerInfo = sellerInfo;
            state.sellerName = sellerInfo.sellerName || '';
            state.userAvatar = sellerInfo.sellerHeader
                ? `${sellerInfo.sellerHeader}?imageMogr2/thumbnail/128x128`
                : defaultUser;
            state.sellerTeamId = sellerTeamId;
            state.needAddress = needAddress;
            state.customCommodityList = customCommodityList;
            state.hasGoods = customCommodityList && customCommodityList.length > 0;
            state.userReceiveAddress = userReceiveAddress || {};
            state.payCount = payCount;
            state.lastPayTime = lastPayTime;
            state.buyerImageHerderList = buyerImageHerderList;
            checkCustomerInfoShow();
            if (customCommodityList && customCommodityList.length > 0) {
                setPageTitle('确认订单');
            }
            // 商户收款功能已被关闭，无法付款
            if (sellerInfo && sellerInfo.prohibitedPay) {
                showDialog({
                    title: '商户收款功能已被关闭，无法付款',
                    confirmButtonText: '关闭'
                });
            }
            typeof callback === 'function' && callback();
        } else if (code === 4004001) {
            // 链接已过期
            state.errorInfo = {
                iconName: 'pending',
                iconColor: '#F1B000',
                title: message,
                infoText: '如有疑问，请联系商家'
            };
        } else if (code === 4004002) {
            const { showImageUrl } = data || '';
            // 订单已被支付
            state.errorInfo = {
                iconName: 'info1',
                iconColor: '#007AFF',
                title: message,
                infoText: '如为本人支付，请点击按钮查看付款记录',
                btnType: 'primary',
                buttonName: '付款记录',
                btnClick: () => {
                    showImageUrl &&
                        showImagePreview({
                            images: [showImageUrl],
                            closeable: true
                        });
                }
            };
        } else if (code === 4009016) {
            // MA绑定异常
            state.errorInfo = {
                iconName: 'info1',
                iconColor: '#007AFF',
                title: message,
                infoText: '请通知商家联系生意云客服'
            };
        } else {
            showToast(message);
        }
    } catch (err) {
        state.isLoading = false;
        console.log(err);
        showToast('获取开单收款信息失败');
        $logger.error(err, {
            pageId: 10002,
            moduleCode: 'ORDER',
            tag: 'getOrderInfo接口异常',
            uri: '/order/create/seller/getOrderInfo'
        });
    }
};

/**
 * 点支付按钮未授权，授权后回来直接拉起支付
 */
const authBackAction = () => {
    getOrderInfo(() => {
        const detail = store.get('DETAIL_INFO');
        if (detail) {
            console.log(detail, 11111);
            state.remark = detail.remark;
            state.userReceiveAddress = detail.userReceiveAddress;
            store.remove('DETAIL_INFO');
        }
        handleConfirmKey();
    });
};

/**
 * 点击支付
 */
const handleConfirmKey = useThrottle(() => {
    const turId = getUrlParam('turId');
    const orderId = getUrlParam('orderId');
    const { payMoney, remark, userReceiveAddress, sellerTeamId, sellerInfo } = state;

    // 商户收款功能已被关闭，无法付款
    if (sellerInfo && sellerInfo.prohibitedPay) {
        showDialog({
            title: '商户收款功能已被关闭，无法付款',
            confirmButtonText: '关闭'
        });
        return;
    }

    // 防止多次点击
    if (state.isSubmit) {
        return;
    }
    state.isSubmit = true;

    // 校验地址
    if ((!userReceiveAddress || !userReceiveAddress.receiveAddressId) && state.needAddress) {
        showToast('请填写收货信息');
        onAddAddress();
        state.isSubmit = false;
        return;
    }

    let receiveAddressId =
        state.needAddress && userReceiveAddress ? userReceiveAddress.receiveAddressId : '';

    const { userStatus, openId } = store.get('USERINFO');
    if (userStatus !== 'AUTHED') {
        store.set('DETAIL_INFO', { remark, userReceiveAddress });
        navigateTo('/auth');
        state.isSubmit = false;
        return;
    }

    const param = {
        sellerTeamId,
        sellerCreateOrderId: orderId,
        turId,
        remark,
        remarkList: [],
        amount: payMoney,
        receiveAddressId,
        openId
    };

    createOrder(param);
}, 3000);

// 创建订单
const createOrder = async (param) => {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
    });
    try {
        const res = await api.fetchPost('createReceiveOrder', param, { hasErr: true });
        const { code, message, data } = res;
        if (code === 0) {
            const { orderId } = data;
            requestPayment({
                orderId,
                turId: param.turId,
                h5PayMerchantNo: state.h5PayMerchantNo
            });
        } else {
            state.isSubmit = false;
            closeToast();
            if (code === 4004002) {
                // 订单已被支付
                showDialog({
                    title: message,
                    confirmButtonText: '确认'
                });
            } else if (code === 4004006 || code === 4004007 || code === 4004012) {
                // 4004006 你非当前商家客户，无法付款
                // 4004007 商户今日收款已达上限，请明天再试
                // 4004012 超出该商户单笔可收款金额上限
                showDialog({
                    title: message,
                    confirmButtonText: '确定'
                });
            } else if (code === 4004008) {
                // 请通知商家完成商户认证
                showDialog({
                    title: message,
                    message: '根据国家法规要求，需要完成商户认证后方可收款',
                    confirmButtonText: '确认'
                });
            } else if (code === 4004009) {
                // 请通知商家申请微信商户号
                showDialog({
                    title: message,
                    message: '应监管要求，需申请微信商户号后可收款',
                    confirmButtonText: '确认'
                });
            } else if (code === 4004010) {
                // 请通知商家联系客服完成签约
                showDialog({
                    title: message,
                    message: '应三方支付机构监管要求，需完成协议签约后方可收款',
                    confirmButtonText: '确认'
                });
            } else {
                showToast(message);
            }
        }
    } catch (err) {
        state.isSubmit = false;
        console.log(err);
        showToast('创建支付单失败');
    }
};

// 发起支付
const requestPayment = async (param) => {
    const res = await api.fetchPost('orderToPay', param, { hasErr: true });
    const { code, message, data } = res;
    if (code === 0) {
        store.remove('AUTH_TYPE');
        webRequestPayment(data);
        closeToast();
    } else if (code === 2002015 || code === 2002013 || code === 2002011) {
        closeToast();
        // 2002015 你非当前商家客户，无法付款
        // 2002013 商家收款已关闭
        // 2002011 该商家当日收款已达上限
        showDialog({
            title: message,
            confirmButtonText: '确定'
        });
    } else if (code === 2002016) {
        // 收款码已失效
        state.errorInfo = {
            iconName: 'error',
            iconColor: '#F1B000',
            title: message,
            infoText: '请通知商家重新生成付款链接'
        };
    } else {
        showToast(message);
    }
    state.isSubmit = false;
};

const onRemarkClose = () => {
    state.showRemarkPopup = false;
};

const onRemarkChange = (value) => {
    state.showRemarkPopup = false;
    state.remark = value;
    checkCustomerInfoShow();
};

const onAddRemark = () => {
    state.showRemarkPopup = true;
};
/**
 * 显示添加地址
 */
const onAddAddress = () => {
    showAddressPopup.value = true;
    const {
        name = '',
        phone = '',
        province = '',
        city = '',
        area = '',
        detail = ''
    } = state.userReceiveAddress;
    Object.assign(addressState, {
        name,
        phone,
        detail,
        province,
        city,
        area
    });
};

/**
 * 关闭地址
 */
const onAddressClose = () => {
    showAddressPopup.value = false;
};

/**
 * 提交地址
 */
const onAddressChange = (value) => {
    state.userReceiveAddress = value;
    showAddressPopup.value = false;
    checkCustomerInfoShow();
};

// 预览图片
const onPreviewImage = (curImage) => {
    if (!curImage) return;
    const images = state.customCommodityList
        .filter((item) => item.imageUrl)
        .map((item) => item.imageUrl);
    const startPosition = images.findIndex((item) => item === curImage);
    showImagePreview({
        images,
        startPosition
    });
};

const handleCustomerRecord = () => {
    state.showCustomerRecord = true;
};

/**
 * 检查是否仅显示客户购买信息
 */
const checkCustomerInfoShow = () => {
    if (state.remark || state.needAddress) {
        state.onlyShow = false;
    } else {
        state.onlyShow = true;
    }
};

defineExpose({ getOrderInfo, authBackAction, handleConfirmKey });
</script>

<template>
    <c-page :loading="state.isLoading">
        <c-result
            v-if="state.errorInfo"
            :padding-top="60"
            :icon-name="state.errorInfo.iconName"
            :icon-color="state.errorInfo.iconColor"
            :title="state.errorInfo.title"
            :info-text="state.errorInfo.infoText"
            :btn-type="state.errorInfo.btnType"
            :btn-name="state.errorInfo.buttonName"
            @btn-click="state.errorInfo.btnClick"
        ></c-result>
        <div class="order-pay" v-if="!state.errorInfo && !state.hasGoods">
            <div class="user-info">
                <img class="header-img" :src="state.userAvatar" />
                <div class="seller-info">
                    <div class="name ellipsis-one">{{ state.sellerName }}</div>
                </div>
            </div>
            <div class="pay-content">
                <div class="input-section">
                    <div class="label"> 付款金额 </div>
                    <div class="input-box">
                        <c-price
                            :price="state.payMoney"
                            :unit-size="28"
                            :unit-space="4"
                            :size="44"
                            :is-wan="false"
                            :is-simple="false"
                        />
                    </div>
                </div>
                <div class="content-box">
                    <div class="cell-group">
                        <div
                            class="activity-info"
                            :style="`border-radius: ${
                                state.onlyShow ? '10px' : '10px 10px 0 10px'
                            };border-bottom: ${state.onlyShow ? 'none' : '1px solid #ffffff'};`"
                            @click="handleCustomerRecord"
                            v-if="state.payCount > 0"
                        >
                            <div class="left-box">
                                <div
                                    style="height: 20px"
                                    v-for="(item, index) in state.buyerImageHerderList"
                                    :key="index"
                                >
                                    <img
                                        wx:if="{{index < 3}}"
                                        :src="
                                            !item || item === '/images/default-goods.png'
                                                ? defaultGood
                                                : item + '?imageMogr2/thumbnail/40x40'
                                        "
                                        class="buyer-img"
                                        :style="`z-index:${
                                            state.buyerImageHerderList.length - index - 1
                                        };margin-right: ${
                                            state.buyerImageHerderList.length - 1 > index
                                                ? '-10px'
                                                : '0'
                                        }`"
                                    />
                                </div>
                                <div class="time">{{ state.lastPayTime }}</div>
                            </div>
                            <div class="right-box">
                                <div class="person-num">{{ state.payCount }}人已付款</div>
                                <c-icon name="arrow" size="17" color="#07C160" />
                            </div>
                        </div>
                        <van-cell
                            class="note-cell"
                            :style="{ borderRadius: state.remark ? '10px 10px 0 0' : '10px' }"
                            icon-prefix="icon"
                            icon="message1"
                            is-link
                            v-if="state.needAddress"
                            :border="state.remark"
                            @click="onAddAddress"
                        >
                            <template #icon>
                                <c-icon name="location1" color="#555555" size="20" />
                            </template>
                            <template #right-icon>
                                <c-icon name="arrow" color="#bbbbbb" size="20" />
                            </template>
                            <template #title>
                                <div>
                                    <div
                                        class="title"
                                        v-if="
                                            state.userReceiveAddress.name ||
                                            state.userReceiveAddress.phone
                                        "
                                    >
                                        {{ state.userReceiveAddress.name }}
                                        {{ state.userReceiveAddress.phone }}
                                    </div>
                                    <div v-else class="title">请填写收货信息</div>
                                    <div class="desc" v-if="state.userReceiveAddress.province">
                                        {{ state.userReceiveAddress.province
                                        }}{{ state.userReceiveAddress.city
                                        }}{{ state.userReceiveAddress.area
                                        }}{{ state.userReceiveAddress.detail }}
                                    </div>
                                </div>
                            </template>
                        </van-cell>
                        <van-cell
                            class="note-cell"
                            v-if="state.remark"
                            :style="{
                                borderRadius: state.needAddress ? ' 0 0 10px 10px' : '10px'
                            }"
                            :title="state.remark"
                            icon-prefix="icon"
                            icon="message1"
                            is-link
                            @click="onAddRemark"
                        >
                            <template #icon>
                                <c-icon name="message1" color="#555555" size="20" />
                            </template>
                            <template #right-icon>
                                <c-icon name="arrow" color="#bbbbbb" size="20" />
                            </template>
                        </van-cell>
                    </div>
                    <div class="add-remark" v-if="!state.remark" @click="onAddRemark">添加备注</div>
                </div>
                <div class="footer-box">
                    <div class="key-confirm" @click.stop="handleConfirmKey"> 立即支付 </div>
                </div>
            </div>
        </div>
        <!-- 有商品场景 -->
        <div class="order-goods-pay" v-if="!state.errorInfo && state.hasGoods">
            <div class="header-bg">
                <van-cell
                    class="address-info"
                    icon-prefix="icon"
                    is-link
                    v-if="state.needAddress"
                    :border="false"
                    @click="onAddAddress"
                >
                    <template #icon>
                        <c-icon
                            style="margin-right: 12px"
                            name="location"
                            color="#07C160"
                            size="20"
                        />
                    </template>
                    <template #right-icon>
                        <c-icon name="arrow" color="#DDDDDD" size="20" />
                    </template>
                    <template #title>
                        <div
                            class="title"
                            v-if="state.userReceiveAddress.name || state.userReceiveAddress.phone"
                        >
                            {{ state.userReceiveAddress.name }}
                            {{ state.userReceiveAddress.phone }}
                        </div>
                        <div v-else class="title">请填写收货信息</div>
                        <div class="detail">{{ state.userReceiveAddress.detail }}</div>
                        <div class="desc" v-if="state.userReceiveAddress.province">
                            {{ state.userReceiveAddress.province }}{{ state.userReceiveAddress.city
                            }}{{ state.userReceiveAddress.area }}
                        </div>
                    </template>
                </van-cell>
                <div class="order-goods">
                    <div class="user-info">
                        <img class="avatar" :src="state.userAvatar" />
                        <div class="name ellipsis-one">{{ state.sellerName }}</div>
                    </div>
                    <div class="goods-info">
                        <div
                            class="good-item"
                            v-for="(item, index) in state.customCommodityList"
                            :key="index"
                            @click="onPreviewImage(item.imageUrl)"
                        >
                            <img
                                :src="
                                    !item.imageUrl || item.imageUrl === '/images/default-goods.png'
                                        ? defaultGood
                                        : `${item.imageUrl}?imageMogr2/thumbnail/180x180/crop/180x180/gravity/center`
                                "
                                class="good-poster"
                            />
                            <div class="good-title">{{ item.content }}</div>
                        </div>
                    </div>
                    <div
                        class="activity-info"
                        @click="handleCustomerRecord"
                        v-if="state.payCount > 0"
                    >
                        <div class="left-box">
                            <div
                                style="height: 20px"
                                v-for="(item, index) in state.buyerImageHerderList"
                                :key="index"
                            >
                                <img
                                    wx:if="{{index < 3}}"
                                    :src="
                                        !item || item === '/images/default-goods.png'
                                            ? defaultGood
                                            : item + '?imageMogr2/thumbnail/40x40'
                                    "
                                    class="buyer-img"
                                    :style="`z-index:${
                                        state.buyerImageHerderList.length - index - 1
                                    };margin-right: ${
                                        state.buyerImageHerderList.length - 1 > index
                                            ? '-10px'
                                            : '0'
                                    }`"
                                />
                            </div>
                            <div class="time">{{ state.lastPayTime }}</div>
                        </div>
                        <div class="right-box">
                            <div class="person-num">{{ state.payCount }}人已付款</div>
                            <c-icon name="arrow" size="17" color="#07C160" />
                        </div>
                    </div>
                </div>
                <div class="remark-box">
                    <span style="margin-right: 8px">{{ state.remark }}</span>
                    <span class="add-remark" @click="onAddRemark">
                        {{ state.remark ? ' 修改备注' : '添加备注' }}
                    </span>
                </div>
            </div>
            <div class="footer-box">
                <div class="price-box">
                    <c-price
                        :price="state.payMoney"
                        :unit-size="24"
                        :size="40"
                        :is-wan="false"
                        :is-simple="false"
                    />
                </div>
                <div class="key-confirm" @click.stop="handleConfirmKey"> 立即支付 </div>
            </div>
        </div>
    </c-page>
    <!-- 地址popup -->
    <CreateRemark
        :show="state.showRemarkPopup"
        :init-data="state.remark"
        @close="onRemarkClose"
        @change="onRemarkChange"
    ></CreateRemark>
    <CreateAddress
        :show="showAddressPopup"
        :init-data="addressState"
        @close="onAddressClose"
        @change="onAddressChange"
    >
    </CreateAddress>
    <CustomerRecord
        v-model:show="state.showCustomerRecord"
        :order-id="state.sellerTeamId"
    ></CustomerRecord>
</template>

<style scoped lang="less">
@import './index.less';
</style>
